package cn.com.idmy.auth.oauth.token;

import cn.com.idmy.auth.context.Request;
import cn.com.idmy.auth.model.AuthCredential;
import cn.com.idmy.auth.model.AuthPrincipal;
import cn.com.idmy.auth.oauth.OauthJwtManager;
import cn.com.idmy.auth.oauth.model.AccessTokenOut;
import lombok.Data;

@Data
public class OauthTokenPasswordImpl implements OauthToken {
    protected OauthJwtManager oauthJwtManager;

    @Override
    public AccessTokenOut getToken(Request request) {
        PasswordIn in = request.getParams().toJavaObject(PasswordIn.class);
        in.setUri(request.getUri());

        AuthPrincipal<?, ?> principal = oauthJwtManager.getAuthenticator().authenticate(AuthCredential.builder()
                .account(in.getUsername())
                .password(in.getPassword())
                .captcha(in.getCaptcha())
        );

        Object id = principal.getPrincipalId();
        oauthJwtManager.getLoginManager().login(id);
        return oauthJwtManager.createAccessToken(id, in);
    }
}
